package co.fitstart.coach.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import co.fitstart.coach.entity.security.Login;
import co.fitstart.coach.service.MessageService;
import co.fitstart.coach.service.PrincipalService;
import co.fitstart.coach.web.resolver.Secure;
import co.fitstart.entity.principal.Principal;

/**
 * 
 * @author wilson
 * @author lidan
 */
@Controller
@RequestMapping("")
public class HomeController {

    @Autowired
    private MessageService messageService;
    
    @Autowired
    private PrincipalService principalService;
    
    /**
     * View coach's home page
     * 
     *   - only check new message
     * 
     * @param login
     * @return
     */
    @RequestMapping(value = { "", "/home"}, method = RequestMethod.GET)
    public ModelAndView home(@Secure Login login) {
        
        ModelAndView modelAndView = new ModelAndView("coach-home");
        
        Principal principal = principalService.load(Principal.class, login.getId());
        
        if(principal.isCoach()) {
            
            // tips if there are new messages
            int newMessageCount = messageService.countNewMessage(principal);
            
            modelAndView.addObject("login", login);
            modelAndView.addObject("newMessage", newMessageCount);
            
        } else {
            
            modelAndView.setViewName("authorize-error");
            
        }
        
        return modelAndView;
    
    }

}
